﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Mystery.SharePoint
{
	/// <summary>
	/// Extension methods for SPPropertyBag
	/// </summary>
	public static class SPPropertyBagExtensions
	{
		/// <summary>
		/// Writes a value to the property bag
		/// </summary>
		/// <param name="properties"></param>
		/// <param name="key">The key of the property</param>
		/// <param name="value">The value of the property</param>
		/// <returns>True if the property bag was updated, otherwise false</returns>
		public static bool Write(this SPPropertyBag properties, string key, object value)
		{
			if (properties == null) throw new ArgumentNullException("properties");

			string v = (value == null) ? "" : value.ToString();

			// checking an existing value
			if (properties.ContainsKey(key) == true)
			{
				// only touch the property bag if the value has actually changed
				if (string.Compare(properties[key], v, StringComparison.OrdinalIgnoreCase) != 0)
				{
					properties[key] = v;
					return true;
				}
			}
			else // value doesn't exist
			{
				properties.Add(key, v);
				return true;
			}
			return false;
		}
		
		/// <summary>
		/// Reads a value from the property bag
		/// </summary>
		/// <param name="properties"></param>
		/// <param name="key">The property key used to find the value</param>
		/// <param name="defaultValue">A value to use if the key doesn't exist in the property bag</param>
		/// <returns></returns>
		public static string Read(this SPPropertyBag properties, string key, string defaultValue)
		{
			if (properties == null) throw new ArgumentNullException("properties");

			// the property exists so we can return the actual value
			if (properties.ContainsKey(key) == true)
			{
				return properties[key];
			}
			// property does not exists so we return a default value
			return defaultValue;
		}
	}
}
